package com.hdy.javachatroomdemo.Controller;

import com.hdy.javachatroomdemo.Config.OSSProperties;
import com.hdy.javachatroomdemo.Config.OSSService;
import com.hdy.javachatroomdemo.Config.LocalFileService;
import com.hdy.javachatroomdemo.Model.Message;
import com.hdy.javachatroomdemo.Model.MessageResponse;
import com.hdy.javachatroomdemo.Model.OSSResult;
import com.hdy.javachatroomdemo.constant.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Path;

@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {
    @Autowired
    OSSService ossService;
    @Autowired
    OSSProperties ossProperties;
    @Autowired
    LocalFileService localFileService;
    @RequestMapping("/upload")
    public MessageResponse upload(MultipartFile file){
        if(file.isEmpty()){
            log.error("上传文件为空");
            return null;
        }
        
        MessageResponse message = new MessageResponse();
        message.setType(Constants.FILE);
        
        try {
            // 优先使用本地存储
            String fileName = localFileService.uploadFile(file);
            message.setContent(fileName);
            log.info("文件已上传到本地存储: {}", fileName);
            return message;
        } catch (IOException e) {
            log.error("本地文件上传失败，尝试使用OSS", e);
            
            // 如果本地存储失败，使用OSS
            OSSResult ossResult = ossService.uploadFile(file);
            if(ossResult.getSuccess()){
                message.setContent(ossResult.getFileName());
                log.info("文件已上传到OSS: {}", ossResult.getFileName());
                return message;
            }
        }
        
        log.error("文件上传失败");
        return message;
    }
    @RequestMapping("/download")
    public MessageResponse download(String fileName){
        if(fileName == null || fileName.isEmpty()){
            log.error("下载文件路径为空");
            return null;
        }
        
        log.info("请求下载文件: {}", fileName);
        
        MessageResponse message = new MessageResponse();
        message.setType(Constants.FILE);
        
        // 优先使用本地文件存储，如果不存在则使用OSS
        if (localFileService.fileExists(fileName)) {
            String downloadUrl = localFileService.getDownloadUrl(fileName);
            message.setContent(downloadUrl);
            log.info("本地文件下载URL: {}", downloadUrl);
        } else {
            // 使用OSS下载URL
            String downloadUrl = ossProperties.getDownloadUrl() + fileName;
            message.setContent(downloadUrl);
            log.info("OSS文件下载URL: {}", downloadUrl);
        }
        
        return message;
    }
    
    /**
     * 本地文件下载端点
     */
    @GetMapping("/local/{fileName:.+}")
    public ResponseEntity<Resource> downloadLocalFile(@PathVariable String fileName) {
        try {
            Path filePath = localFileService.getFilePath(fileName);
            Resource resource = new UrlResource(filePath.toUri());
            
            if (resource.exists() && resource.isReadable()) {
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
                        .contentType(MediaType.APPLICATION_OCTET_STREAM)
                        .body(resource);
            } else {
                log.error("文件不存在或无法读取: {}", fileName);
                return ResponseEntity.notFound().build();
            }
        } catch (MalformedURLException e) {
            log.error("文件路径错误: {}", fileName, e);
            return ResponseEntity.badRequest().build();
        }
    }
}
